package com.hust360.percent.pojo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import android.database.Cursor;

import com.hust360.percent.PercentApplication;
import com.hust360.percent.pojo.Appraise.AppraiseDAO;

public class AppraiseDAOImpl implements AppraiseDAO {

	@Override
	public Appraise findById(Long id) {
		Appraise appraise = null;
		Cursor c = PercentApplication.localDB.rawQuery(
				"SELECT * FROM appraise WHERE id='" + id + "'", null);
		if (c.moveToNext()) {
			appraise = new AppraiseLocal();
			appraise.content = c.getString(c.getColumnIndex(Appraise.CONTENT));
			appraise.dscid = c.getLong(c.getColumnIndex(Appraise.DSCID));
			appraise.id = c.getLong(c.getColumnIndex(Appraise.CONTENT));
			appraise.rate = c.getFloat(c.getColumnIndex(Appraise.RATE));
			appraise.uid = c.getLong(c.getColumnIndex(Appraise.UID));
		}
		c.close();
		return appraise;
	}

	@Override
	public List<Appraise> findWithMap(Map<String, String> map) {
		final List<String> columns = Arrays.asList(Appraise.COLUMNS);
		String value = null;
		StringBuffer selection = new StringBuffer();
		List<Appraise> list = null;
		Appraise appraise = null;
		
		for (String key : map.keySet()) {
			value = map.get(key);
			if (columns.contains(key) && value != null) {
				selection.append(key + "='" + value + "' AND ");
				value = null;
			}
		}
		selection.append("'1'='1'");
		Cursor c = PercentApplication.localDB.rawQuery(
				"SELECT * FROM appraise WHERE " + selection.toString(), null);
		list = new ArrayList<Appraise>(c.getCount());
		while (c.moveToNext()) {
			appraise = new AppraiseLocal();
			appraise.content = c.getString(c.getColumnIndex(Appraise.CONTENT));
			appraise.dscid = c.getLong(c.getColumnIndex(Appraise.DSCID));
			appraise.id = c.getLong(c.getColumnIndex(Appraise.CONTENT));
			appraise.rate = c.getFloat(c.getColumnIndex(Appraise.RATE));
			appraise.uid = c.getLong(c.getColumnIndex(Appraise.UID));
			list.add(appraise);
		}
		c.close();
		return list;
	}

}
